package com.gate.way.demo.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author wangzhilong
 * @date 2021/3/19
 */
@Component
public class ElapsedFilter implements WebFilter, Ordered {

    private static final Logger log = LoggerFactory.getLogger(ElapsedFilter.class);

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        log.info("业务开始处理。");
        long start = System.currentTimeMillis();
        return chain
                .filter(exchange)
                // filter是一去一回的操作，filter(exchange) 去的操作 then() 回来的操作
                .then(Mono.fromRunnable(() -> log.info("业务处理完成：{}(ms)",(System.currentTimeMillis() - start))));
    }
}
